package models.helper;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import helper.GlobalConfig;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import models.constants.DeletedStatus;
import models.constants.Gender;
import models.merchant.Merchant;
import models.weixin.WebUser;
import models.weixin.WeixinData;
import play.Logger;
import utils.ObjectUtil;

import java.util.Date;


/**
 * 微信公众号工具类.
 */
public class WxMpHelper {

    private static WxMpConfigStorage wxMpConfigStorage = null;

    /**
     * 通过CorpApp得到微信配置.
     */
    public static WxMpConfigStorage getWxMpConfigStorage() {
        if (wxMpConfigStorage == null) {
            WeixinData weixinData = WeixinData.findByWeixinDataId(GlobalConfig.WEIXIN_DATE_ID);
            wxMpConfigStorage = initWxMpConfigStorage(weixinData);
        }
        return wxMpConfigStorage;
    }

    /**
     * 通过CorpApp得到微信配置.
     */
    public static WxMpConfigStorage getWxMpConfigStorage(Merchant merchant) {
//        if (wxMpConfigStorage == null || !wxMpConfigStorage.getAppId().equals(merchant.weixinData.appId)) {
            Logger.info("初始化 ：WxMpConfigStorage");
            wxMpConfigStorage = initWxMpConfigStorage(merchant);
//        }
        return wxMpConfigStorage;
    }

    /**
     * 通过CorpApp得到微信配置.
     */
    public static WxMpConfigStorage getWxMpConfigStorage(WeixinData weixinData) {
//        if (wxMpConfigStorage == null || !wxMpConfigStorage.getAppId().equals(merchant.weixinData.appId)) {
        Logger.info("初始化 WxMpConfigStorage");
        wxMpConfigStorage = initWxMpConfigStorage(weixinData);
//        }
        return wxMpConfigStorage;
    }

    private static WxMpConfigStorage initWxMpConfigStorage(Merchant merchant) {
        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpConfigStorage.setAppId(merchant.weixinData.appId);     // 设置微信公众号的appid
        wxMpConfigStorage.setSecret(merchant.weixinData.appSecure);    // 设置微信公众号的app corpSecret
        wxMpConfigStorage.setToken(merchant.weixinData.appToken);       // 设置微信公众号的token
        wxMpConfigStorage.setAesKey(merchant.weixinData.appAesKey);      // 设置微信公众号的EncodingAESKey
        return wxMpConfigStorage;
    }

    private static WxMpConfigStorage initWxMpConfigStorage(WeixinData weixinData) {
        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpConfigStorage.setAppId(weixinData.appId);     // 设置微信公众号的appid
        wxMpConfigStorage.setSecret(weixinData.appSecure);    // 设置微信公众号的app corpSecret
        wxMpConfigStorage.setToken(weixinData.appToken);       // 设置微信公众号的token
        wxMpConfigStorage.setAesKey(weixinData.appAesKey);      // 设置微信公众号的EncodingAESKey
        return wxMpConfigStorage;
    }

    private static WxMpConfigStorage initWxMpConfigStorage() {
        WxMpInMemoryConfigStorage wxMpConfigStorage = new WxMpInMemoryConfigStorage();
        wxMpConfigStorage.setAppId(GlobalConfig.WEIXIN_APP_ID);     // 设置微信公众号的appid
        wxMpConfigStorage.setSecret(GlobalConfig.WEIXIN_APP_SECURET);    // 设置微信公众号的app corpSecret
        wxMpConfigStorage.setToken(GlobalConfig.WEIXIN_TOKEN);       // 设置微信公众号的token
        wxMpConfigStorage.setAesKey(GlobalConfig.WEIXIN_AES_KEY);      // 设置微信公众号的EncodingAESKey
        return wxMpConfigStorage;
    }

    /**
     * 通过ConfigStore得到微信服务接口.
     */
    public static WxMpService getWxMpService(WxMpConfigStorage wxMpConfigStorage) {
        WxMpServiceImpl wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxMpConfigStorage);
        return wxMpService;
    }

    /**
     * 通过ConfigStore得到微信服务接口.
     */
    public static WxMpService getWxMpService() {
        WxMpServiceImpl wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(getWxMpConfigStorage());
        return wxMpService;
    }

    public static WxPayService getWxPayService(WeixinData weixinData) {
        WxPayServiceImpl wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(initWxPayConfig(weixinData));
        return wxPayService;
    }

    public static WxPayService getWxPayService() {
        WxPayServiceImpl wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(initWxPayConfig());
        return wxPayService;
    }

    public static WxPayService getWxPayService(WebUser webUser) {
        WxPayServiceImpl wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(initWxPayConfig(webUser));
        return wxPayService;
    }

    public static WxPayConfig initWxPayConfig() {
        WeixinData weixinData = WeixinData.findById(GlobalConfig.WEIXIN_DATE_ID);
        return initWxPayConfig(weixinData);
    }

    public static WxPayConfig initWxPayConfig(WebUser webUser) {
        WeixinData weixinData = WeixinData.findById(webUser.weixinData.id);
        return initWxPayConfig(weixinData);
    }

    public static WxPayConfig initWxPayConfig(WeixinData weixinData) {
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(weixinData.appId);
        wxPayConfig.setMchId(weixinData.mchId);
        wxPayConfig.setMchKey(weixinData.payKey);
        wxPayConfig.setKeyPath(weixinData.payPath);
        return wxPayConfig;
    }


    /**
     * 转换wxMpUser为User.
     */
    public static WebUser createOrUpdateUserFromWxMpUser(WeixinData weixinData, WxMpUser wxMpUser , String dcode) throws Exception {
        return findOrCreateMerchantWxUser(weixinData, wxMpUser , dcode);
    }

    /**
     * 转换wxMpUser为User.
     */
    public static WebUser createOrUpdateUserFromWxMpUser(WeixinData weixinData, WxMpUser wxMpUser) {
        return findOrCreateMerchantWxUser(weixinData, wxMpUser , null);
    }



    /**
     * 查询出商户指定OpenId的用户.
     */
    public static WebUser findOrCreateMerchantWxUser(WeixinData weixinData, WxMpUser wxMpUser , String dcode) {
        Logger.info("wxMpUser.getOpenId() : %s" , wxMpUser.getOpenId());
        WebUser webUser = WebUser.find("openId=?1 and deleted = ?2", wxMpUser.getOpenId() , DeletedStatus.UN_DELETED).first();
        Logger.info("WebUser : %s" , webUser);
        if (webUser == null) {
            webUser = new WebUser();
            webUser.createAt = new Date();
            webUser.deleted = DeletedStatus.UN_DELETED;
            webUser.weixinData = weixinData;
            webUser.openId = wxMpUser.getOpenId();
            webUser.nickName = wxMpUser.getNickname();
            webUser.subcribed = Boolean.FALSE;
            webUser.introduceCode = dcode;
            webUser.city = wxMpUser.getCity();
            webUser.country = wxMpUser.getCountry();
            webUser.language = wxMpUser.getLanguage();
            webUser.headImgUrl = wxMpUser.getHeadImgUrl();
            webUser.isFirst = true;
            if ("1".equals(wxMpUser.getSex()) || "男".equals(wxMpUser.getSex())) {
                webUser.sex = Gender.MALE;
            } else if ("2".equals(wxMpUser.getSex()) || "女".equals(wxMpUser.getSex())) {
                webUser.sex = Gender.FEMALE;
            } else {
                webUser.sex = Gender.UNKNOWN;
            }
            webUser.subcribed = wxMpUser.getSubscribe();
            webUser.save();
        }
        webUser.identityCode = ObjectUtil.coverNumber(webUser.id.intValue() , 6);
        webUser.save();
        return webUser;
    }

    public static WebUser getUserFromOpenId(String wxOpenId) {
        Logger.info("getUserFromOpenId  WxOpenId : %s" , wxOpenId);
        return WebUser.findByOpenId(wxOpenId);
    }

}
